package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDTO
     * @return
     */
    public void save(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //插入一条套餐数据
        setmealMapper.insert(setmeal);
        // 获取生成的套餐id
        Long id = setmeal.getId();
        // 获取 SetmealDTO 中关联的菜品列表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        // 遍历菜品列表，设置每个菜品的套餐 ID
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
        }
        //将菜品与套餐关系插入进去
        setmealDishMapper.insertBatch(setmealDishes);
        // 删除redis缓存中的菜品数据
        cleanCache(setmealDTO.getCategoryId().toString());
    }

    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    public PageResult page(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.page(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除套餐
     * @param ids
     * @return
     */
    public void delete(List<Long> ids) {
        if (!ids.isEmpty()){
            //遍历套餐id列表，检查套餐状态
            ids.forEach(id->{
               Setmeal setmeal = setmealMapper.getById(id);
                // 如果套餐状态为启用，则不允许删除
                if(setmeal.getStatus().equals(StatusConstant.ENABLE)){
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
               }
            });
               ids.forEach(id->{
                   // 删除套餐
                   setmealMapper.deleteById(id);
                   // 删除与套餐关联的菜品
                   setmealDishMapper.deleteBySetmealId(id);
               });
        }
        //删除redis缓存中的菜品数据
        cleanCache("*");
    }

    /**
     * 根据id查询套餐和套餐菜品关系
     *
     * @param id
     * @return
     */
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.getById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);

        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);

        return setmealVO;
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        //1、修改套餐表，执行update
        setmealMapper.update(setmeal);
        //套餐id
        Long setmealId = setmealDTO.getId();
        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteBySetmealId(setmealId);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        //3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.insertBatch(setmealDishes);
        //删除redis缓存中的菜品数据
        cleanCache("*");
    }

    /**
     * 启用禁用套餐信息
     * @param status
     * @param id
     * @return
     */
    public void startOrStop(Integer status, Long id) {
        //若status为启用状态
        if (status.equals(StatusConstant.ENABLE)){
            //查询关联菜品
            List<Dish> dishIds =  dishMapper.getBySetmealId(id);
            if(!dishIds.isEmpty()&&dishIds.size()>0){
                dishIds.forEach(ids->{
                    //若存在禁用菜品，则抛出异常
                    if(ids.getStatus().equals(StatusConstant.DISABLE)){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        //更新套餐状态至数据库
        Setmeal setmeal = Setmeal.builder().status(status).id(id).build();
        setmealMapper.update(setmeal);
        //删除redis缓存中的菜品数据
        cleanCache("*");
    }
    /**
     * 根据分类id查询套餐
     * @param categoryId
     * @return
     */
    public List<Setmeal> getByCategoryId(Long categoryId) {
        Setmeal setmeal = Setmeal.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return setmealMapper.getByCategoryId(setmeal);
    } 

    /**
     * 根据套餐id查询菜品
     *
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

    public void cleanCache(String suffix){
        log.info("清理缓存中指定的Key：{}","setmeal:cache:"+suffix);
        Set<Object> keys = redisTemplate.keys("setmeal:cache:" + suffix);
        assert keys!=null;
        redisTemplate.delete(keys);
    }
}
